<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="爱洞ID" prop="platformId">
        <el-input v-model="queryParams.platformId" placeholder="请输入爱洞ID" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="支付方式" prop="payType">
        <el-select v-model="queryParams.payType" placeholder="请选择支付方式" clearable>
          <el-option v-for="dict in dict.type.app_pay_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="平台订单号" prop="orderId">
        <el-input v-model="queryParams.orderId" placeholder="请输入平台订单号" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="第三方订单号" prop="thirdId">
        <el-input v-model="queryParams.thirdId" placeholder="请输入第三方订单号" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>

      <el-form-item label="充值类型" prop="rechargeType">
        <el-select v-model="queryParams.rechargeType" placeholder="请选择充值类型" clearable @change="getList">
          <el-option v-for="dict in dict.type.recharge_type" :key="dict.value" :label="dict.label"
                     :value="parseInt(dict.value)"/>
        </el-select>
      </el-form-item>

      <el-form-item label="充值结果" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择充值类型" clearable>
          <el-option v-for="dict in dict.type.recharge_result" :key="dict.value" :label="dict.label"
                     :value="parseInt(dict.value)"/>
        </el-select>
      </el-form-item>

      <el-form-item label="充值时间" prop-="createTime">
        <el-date-picker v-model="queryParams.payTimeStart" type="datetime" placeholder="请选择开始时间"
                        value-format="yyyy-MM-dd HH:mm:ss" clearable/>
        至
        <el-date-picker v-model="queryParams.payTimeEnd" type="datetime" placeholder="请选择结束时间"
                        value-format="yyyy-MM-dd HH:mm:ss" clearable/>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:payDetail:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:appUser:addWallet']"
        >手动充值</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="payDetailList" :summary-method="getSummaries" show-summary>
      <el-table-column label="爱动ID" align="center" prop="platformId">
        <template slot-scope="scope">
          <a v-if="scope.row.sex === 1" style="color: #FF6EC7" @click="toUserInfo(scope.row.platformId)">{{ scope.row.platformId }}
          </a>
          <a v-else style="color: #7099F9" @click="toUserInfo(scope.row.platformId)">{{ scope.row.platformId }}
          </a>
        </template>
      </el-table-column>
      <el-table-column label="平台订单号" align="center" prop="orderId"/>
      <el-table-column label="第三方订单号" align="center" prop="thirdId"/>
      <el-table-column label="客户端类型" align="center" prop="branch">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_branch" :value="scope.row.branch"/>
        </template>
      </el-table-column>
      <el-table-column label="支付金额" align="center" prop="cnyPrice"/>

      <!--     <el-table-column label="充值类型" align="center" prop="rechargeType" />
              <template slot-scope="scope">
                <dict-tag :options="dict.type.recharge_type" :value="scope.row.rechargeType" />
              </template>
            </el-table-column> -->

      <el-table-column label="支付方式" align="center" prop="payType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.app_pay_type" :value="scope.row.payType"/>
        </template>
      </el-table-column>

      <template v-if="queryParams.rechargeType===1">
        <el-table-column label="充值金币" align="center" prop="gold"/>
        <el-table-column label="充值前金币余额" align="center" prop="beforeGoldBalance"/>
        <el-table-column label="充值后金币余额" align="center" prop="afterGoldBalance"/>
      </template>

      <template v-else>
        <el-table-column label="充值月数" align="center" prop="month"/>
        <el-table-column label="剩余到期时间" align="center" prop="afterExpireTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.afterExpireTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="充值前VIP剩余时间" align="center" prop="beforeExpireTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.beforeExpireTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
      </template>


      <el-table-column label="充值结果" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.recharge_result" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="充值时间" align="center" prop="createTime"/>
      <el-table-column label="支付时间" align="center" prop="updateTime"/>

      <el-table-column label="备注" align="center" prop="remark"/>

    </el-table>


    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 手动充值 -->
    <el-dialog title="手动充值" :visible.sync="open" width="500px" append-to-body>

      <el-form :inline="true" :model="rechargeBo" class="demo-form-inline">

        <el-form-item label="爱洞ID">
          <el-input type="number" v-model="rechargeBo.platformId" placeholder="请输入爱洞ID"
                    style="width: 217px;"/>
        </el-form-item>

        <el-form-item label="支付金额">
          <el-input type="number" v-model="rechargeBo.cnyPrice" placeholder="请输入支付金额"
                    style="width: 217px;"/>
        </el-form-item>

        <el-form-item label="到账金币">
          <el-input type="number" v-model="rechargeBo.gold" placeholder="请输入到账金币"
                    style="width: 217px;"/>
        </el-form-item>

        <el-form-item label="备注">
          <el-input type="textarea" v-model="rechargeBo.remark" placeholder="请输入备注"
                    style="width: 217px;"/>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="toSend">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>

    </el-dialog>
  </div>
</template>

<script>
import {
  addPayDetail,
  delPayDetail,
  getPayDetail,
  listPayDetail,
  planSelect,
  manualRecharge,
  updatePayDetail
} from "@/api/service/pay/payDetail";

export default {
  name: "PayDetail",
  dicts: ['recharge_type', 'recharge_result', 'sys_branch', 'app_pay_type'],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 充值明细表格数据
      payDetailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: undefined,
        orderId: undefined,
        thirdId: undefined,
        branch: undefined,
        status: undefined,
        beforeGoldBalance: undefined,
        cnyPrice: undefined,
        gold: undefined,
        payType: undefined,
        afterGoldBalance: undefined,
        rechargeType: 1,
        month: undefined,
        afterExpireTime: undefined,
        beforeExpireTime: undefined
      },
      rechargeBo:{},
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      rechargePlans: {}
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getSummaries(param) {

      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, index) => {

        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        if (index !== 4) {
          sums[index] = '/';
          return;
        }
        const values = data.map(item => {
          if (item.status === 1) {
            return Number(item[column.property]) * 100
          } else {
            return 0;
          }
        });
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0) / 100;
          sums[index] += ' 元';
        } else {
          sums[index] = 'N/A';
        }
      });

      return sums;
    },
    /** 查询充值明细列表 */
    getList() {
      this.loading = true;
      listPayDetail(this.queryParams).then(response => {
        this.payDetailList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    handleAdd(){
      this.open = true;
      // this.loading = true;
      // planSelect().then(response => {
      //   this.rechargePlans = response.data;
      //   this.loading = false;
      // });
    },
    toSend() {
      manualRecharge(this.rechargeBo).then(response => {
        this.getList();
        this.rechargeBo = {}
        this.open = false;
      });
    },
    cancel() {
      this.rechargeBo = {}
      this.open = false;
    },
    // 取消按钮
    // cancel() {
    //   this.open = false;
    //   this.reset();
    // },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        userId: undefined,
        orderId: undefined,
        thirdId: undefined,
        branch: undefined,
        status: undefined,
        remark: undefined,
        createTime: undefined,
        createBy: undefined,
        updateTime: undefined,
        updateBy: undefined,
        beforeGoldBalance: undefined,
        cnyPrice: undefined,
        gold: undefined,
        payType: undefined,
        afterGoldBalance: undefined,
        rechargeType: undefined,
        month: undefined,
        afterExpireTime: undefined,
        beforeExpireTime: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    // handleAdd() {
    //   this.reset();
    //   this.open = true;
    //   this.title = "添加充值明细";
    // },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getPayDetail(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改充值明细";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updatePayDetail(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addPayDetail(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除充值明细编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delPayDetail(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/payDetail/export', {
        ...this.queryParams
      }, `payDetail_${new Date().getTime()}.xlsx`)
    },
    /**
     * 点击用户爱动id跳转到用户页面
     * @param platformId
     */
    toUserInfo(platformId) {
      this.$router.push({path: "/user/appUser", query: {id: platformId}});
    }
  }
};
</script>
